package com.gmss.crawler.module.person.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmss.crawler.constants.Base;
import com.gmss.crawler.constants.Constants;
import com.gmss.crawler.entity.AcademicianEntity;
import com.gmss.crawler.enums.AcademicianEnum;
import com.gmss.crawler.enums.CommonEnum;
import com.gmss.crawler.module.company.domain.Company;
import com.gmss.crawler.module.company.service.ICompanyService;
import com.gmss.crawler.module.honor.service.IHonorService;
import com.gmss.crawler.module.paper.domain.Paper;
import com.gmss.crawler.module.paper.service.IPaperService;
import com.gmss.crawler.module.patent.domain.Patent;
import com.gmss.crawler.module.patent.service.IPatentService;
import com.gmss.crawler.module.person.domain.PersonInfo;
import com.gmss.crawler.module.person.service.IPersonInfoService;
import com.gmss.crawler.module.publication.domain.Publication;
import com.gmss.crawler.module.publication.service.IPublicationService;
import com.gmss.crawler.module.resume.domain.Resume;
import com.gmss.crawler.module.resume.service.IResumeService;
import com.gmss.crawler.module.social.service.ISocialService;
import com.gmss.crawler.module.title.domain.PersonTitle;
import com.gmss.crawler.module.title.service.IPersonTitleService;
import com.gmss.crawler.service.*;
import com.gmss.crawler.task.PaperTask;
import com.gmss.crawler.utils.CommonUtils;
import com.gmss.crawler.utils.CrawlerCommonUtils;
import com.gmss.crawler.utils.OkHttp3Util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 人员信息 前端控制器
 * </p>
 *
 * @author Auto-generator
 * @since 2021-10-19
 */
@RestController
@RequestMapping("/personInfo")
public class PersonInfoController extends Base {

    @Resource
    private ICompanyService iCompanyService;
    @Resource
    private PersonalHomeService personalHomeService;
    @Resource
    private IPersonInfoService iPersonInfoService;
    @Resource
    private IPersonTitleService iPersonTitleService;
    @Resource
    private CaeCrawlerService caeCrawlerService;
    @Resource
    private CasCrawlerService casCrawlerService;
    @Resource
    private BaiduBaiKeCrawlerService baiduCrawlerService;
    @Resource
    private WikipediaCrawlerService wikipediaCrawlerService;
    @Resource
    private IPaperService iPaperService;
    @Resource
    private IResumeService iResumeService;
    @Resource
    private ISocialService iSocialService;
    @Resource
    private IHonorService iHonorService;
    @Resource
    private ParseExcelService parseExcelService;
    @Resource
    private ScholarService scholarService;
    @Resource
    private PaperTask paperTask;
    @Resource
    private JQCrawlerService jqCrawlerService;
    @Resource
    private AminerCrawlerService aminerCrawlerService;
    @Resource
    private IPublicationService iPublicationService;
    @Resource
    private IPatentService iPatentService;


    @Value("${img_file_path}")
    private String imgFilePath;

    @Value("${outstand_youth_path}")
    private String outstandYouthPath;

    // 杰青年重名的，数据库已手动导入数据。"郭雷", "张杰", "朱敏"
    List<String> JQNameList = new ArrayList<String>() {{
        add("郭雷");
        add("张杰");
        add("朱敏");
        add("李林");
        add("张军");
        add("赵文智");
        add("陈军");
    }};

    /**
     * 通过id查询
     */
    @GetMapping("/getById/{id}")
    public String getById(@PathVariable(value = "id") Integer id) {
        return respJson(CommonEnum.SUCCESS, iPersonInfoService.getById(id));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    public String save(@RequestBody PersonInfo personInfo) {
        iPersonInfoService.save(personInfo);
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 通过id删除
     */
    @DeleteMapping("/deleteById/{id}")
    public String delete(@PathVariable(value = "id") String ids) {
        String[] idsStrs = ids.split(",");

        for (String id : idsStrs) {

            iPersonInfoService.removeById(Integer.parseInt(id));
        }
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public String updateById(@RequestBody PersonInfo personInfo) {
        iPersonInfoService.updateById(personInfo);
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 查询列表
     */
    @PostMapping("/list")
    public String list(@RequestBody PersonInfoReqVo personInfo) {
        final LambdaQueryWrapper<PersonInfo> lambda = new QueryWrapper<PersonInfo>().lambda();
        buildCondition(lambda, personInfo);
        return respJson(CommonEnum.SUCCESS, iPersonInfoService.list(lambda));
    }


    /**
     * 分页查询
     */
    @PostMapping("/page")
    public String page(@RequestBody PersonInfoReqVo pageParam) {
        final LambdaQueryWrapper<PersonInfo> lambda = new QueryWrapper<PersonInfo>().lambda();
        buildCondition(lambda, pageParam);
        final IPage<PersonInfo> page = iPersonInfoService.page(new Page<>(Constants.PAGE_NO, Constants.PAGE_SIZE), lambda);
        return respJson(CommonEnum.SUCCESS, page);
    }

    /**
     * 中国科学院院士爬取
     *
     * @return
     */
    @PostMapping("/save/cas")
    public String saveCas() {
        List<AcademicianEntity> list = casCrawlerService.crawlerCas();
        saveData(list);
        return respJson(CommonEnum.SUCCESS);
    }

    @PostMapping("/updateCas")
    public String updateCas(@RequestBody String str) throws IOException {

        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);
        JSONObject jsonObject = JSON.parseObject(str);
        if (MapUtils.isEmpty(jsonObject))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        if (!jsonObject.containsKey("year"))
            return respJson(CommonEnum.PARAM_NULL_ERROR, "更新工程院院士当选年不能为空！");

        String year = jsonObject.getString("year");
        List<PersonInfo> list = new ArrayList<>();
        if (StringUtils.equals(year, "2021")) {
            list = casCrawlerService.addData();
            log.info("{}年度科学院院士增选人数：{}", year, list.size());
            List<PersonInfo> list1 = casCrawlerService.addData1();
            log.info("{}年度科学院外籍院士增选人数：{}", year, list1.size());
            if (CollectionUtils.isNotEmpty(list1)) {
                list.addAll(list1);
                log.info("新增2021年科学院院士总人数：{}", list.size());
                iPersonInfoService.verifyDuplicateNamesAndSaveOrUpdate(list);
            }
        }

        return respJson(CommonEnum.SUCCESS, jsonObject.getString("year") + "年度中国科学院院士增选人数：" + list.size());
    }

    /**
     * 中国工程院院士爬取
     *
     * @return
     */
    @PostMapping("/save/cae")
    public String saveCae() {
        List<AcademicianEntity> list = caeCrawlerService.crawlerAca();
        saveData(list);
        return respJson(CommonEnum.SUCCESS);
    }

    @PostMapping("/updateCae")
    public String updateCae(@RequestBody String str) {

        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);
        JSONObject jsonObject = JSON.parseObject(str);
        if (MapUtils.isEmpty(jsonObject))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        if (!jsonObject.containsKey("year"))
            return respJson(CommonEnum.PARAM_NULL_ERROR, "更新工程院院士当选年不能为空！");

        List<AcademicianEntity> list = caeCrawlerService.updateCrawlerAca(jsonObject.getString("year"));
        if (CollectionUtils.isNotEmpty(list)) {
            List<PersonInfo> personInfoList = new ArrayList<>();
            for (AcademicianEntity entity : list) {
                PersonInfo personInfo = new PersonInfo();
                BeanUtil.copyProperties(entity, personInfo);
                personInfoList.add(personInfo);
            }
            iPersonInfoService.verifyDuplicateNamesAndSaveOrUpdate(personInfoList);
        }
        Map<String, String> map = list.stream().collect(Collectors.toMap(AcademicianEntity::getName, AcademicianEntity::getAcademicianTitleValue));

        Map<String, String> valueSortedMap = map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        return respJson(CommonEnum.SUCCESS, jsonObject.getString("year") + "年度中国工程院院士增选人数：" + list.size() + "，人员名单：" + JSON.toJSONString(valueSortedMap));
    }

//    @PostMapping("/savePaperInfoByJQ")
//    public String savePaperInfoByJQ(@RequestBody String str) {
//        JSONObject jsonObject = new JSONObject();
//        if (StringUtils.isNotBlank(str)) {
//            jsonObject = JSONObject.parseObject(str);
//        }
//        // 1994-2019年杰出青年数据
//        List<PersonInfo> list = jqCrawlerService.crawlerOutstanTalents();
//        Map<String, List<PersonInfo>> personInfoGroupMap = list.stream().collect(Collectors.groupingBy(PersonInfo::getElectionYear));
//        // 全球华人专家库-杰青年度列表
////        List<Map<String, Object>> personInfoParamsList = jqCrawlerService.aminerList();
//        List<Map<String, Object>> personInfoParamsList = new ArrayList<>();
//
//        personInfoGroupMap.forEach((yearValue, personInfoList) -> {
//            Map<String, PersonInfo> nameMap = new HashMap<>();
//            // 同年重名人员，2019:石峰、张龙，2014:张强，2009:汪国平，2007：王伟，暂不处理，也没有几个手动解决
//            if (StringUtils.equals(yearValue, "2019")) {
//                nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
//                        && !StringUtils.equalsAny(personInfo.getName(), "石峰", "张龙"))
//                        .collect(Collectors.toMap(PersonInfo::getName, x -> x));
//            } else if (StringUtils.equals(yearValue, "2014")) {
//                nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
//                        && !StringUtils.equalsAny(personInfo.getName(), "张强"))
//                        .collect(Collectors.toMap(PersonInfo::getName, x -> x));
//            } else if (StringUtils.equals(yearValue, "2009")) {
//                nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
//                        && !StringUtils.equalsAny(personInfo.getName(), "汪国平"))
//                        .collect(Collectors.toMap(PersonInfo::getName, x -> x));
//            } else if (StringUtils.equals(yearValue, "2007")) {
//                nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
//                        && !StringUtils.equalsAny(personInfo.getName(), "王伟"))
//                        .collect(Collectors.toMap(PersonInfo::getName, x -> x));
//            } else {
//                nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp())
//                        .collect(Collectors.toMap(PersonInfo::getName, x -> x));
//            }
////            File outstandYouthFile = new File( outstandYouthPath + "youth-" + yearValue + ".txt");
//            File outstandYouthFile = new File("E:\\project\\crawler\\src\\main\\resources\\htmlTest\\jq-杰出青年\\" + "youth-" + yearValue + ".txt");
//            if (outstandYouthFile.exists()) {
//                try {
//                    List<String> yearYouthList = FileUtils.readLines(outstandYouthFile, StandardCharsets.UTF_8);
//                    for (String line : yearYouthList) {
//                        aminerCrawlerService.parseAminerTxt(line, nameMap, yearValue);
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            List<String> nameList = personInfoList.stream().map(PersonInfo::getName).collect(Collectors.toList());
//            List<String> nameList2 = nameMap.entrySet().stream().map(entry -> entry.getKey()).collect(Collectors.toList());
//            List<String> repearList = nameList.stream().filter(item -> !nameList2.contains(item)).collect(Collectors.toList());
//            List<String> repearList1 = nameList2.stream().filter(item -> !nameList.contains(item)).collect(Collectors.toList());
//
//
//            System.out.println(JSON.toJSONString(repearList));
//            System.out.println(JSON.toJSONString(repearList1));
//        });
//
////        if (CollectionUtils.isNotEmpty(personInfoParamsList)) {
////            for (int i = 0; i < personInfoParamsList.size(); i++) {
////                Map<String, Object> personInfoParamsMap = personInfoParamsList.get(i);
////                personInfoParamsMap.put("pageOffset", 0);
////                personInfoParamsMap.put("pageSize", 50);
////                personInfoParamsMap.forEach((key, yearValue) -> {
////                    if (StringUtils.equals(key, "year") && personInfoGroupMap.containsKey(yearValue) && CollectionUtils.isNotEmpty(personInfoGroupMap.get(yearValue))) {
////                        List<PersonInfo> personInfoList = personInfoGroupMap.get(yearValue);
////
////                        Map<String, PersonInfo> nameMap = new HashMap<>();
////                        // 同年重名人员，2019:石峰、张龙，2014:张强，2009:汪国平，2007：王伟，暂不处理，也没有几个手动解决
////                        if (StringUtils.equals(yearValue.toString(), "2019")) {
////                            nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
////                                    && !StringUtils.equalsAny(personInfo.getName(), "石峰", "张龙"))
////                                    .collect(Collectors.toMap(PersonInfo::getName, x -> x));
////                        } else if (StringUtils.equals(yearValue.toString(), "2014")) {
////                            nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
////                                    && !StringUtils.equalsAny(personInfo.getName(), "张强"))
////                                    .collect(Collectors.toMap(PersonInfo::getName, x -> x));
////                        } else if (StringUtils.equals(yearValue.toString(), "2009")) {
////                            nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
////                                    && !StringUtils.equalsAny(personInfo.getName(), "汪国平"))
////                                    .collect(Collectors.toMap(PersonInfo::getName, x -> x));
////                        } else if (StringUtils.equals(yearValue.toString(), "2007")) {
////                            nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
////                                    && !StringUtils.equalsAny(personInfo.getName(), "王伟"))
////                                    .collect(Collectors.toMap(PersonInfo::getName, x -> x));
////                        } else {
////                            nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp())
////                                    .collect(Collectors.toMap(PersonInfo::getName, x -> x));
////                        }
////
////                        log.info("{}年，杰青人数：{}", yearValue, nameMap.size());
//////                       人员信息列表
////                        jqCrawlerService.aminerPersonInfoList(personInfoParamsMap, nameMap);
////                    }
////                });
////            }
////        }
//        if (MapUtils.isNotEmpty(personInfoGroupMap)) {
//            Map<String, Object> queryMap = new HashMap<>();
//            for (Map.Entry<String, List<PersonInfo>> groupMapEntry : personInfoGroupMap.entrySet()) {
//                String year = groupMapEntry.getKey();
//                List<PersonInfo> personInfoList = groupMapEntry.getValue();
////            personInfoGroupMap.forEach((year, personInfoList) -> {
//                if (CollectionUtils.isNotEmpty(personInfoList)) {
//                    for (PersonInfo personInfo : personInfoList) {
//                        PersonTitle personTitle = new PersonTitle();
//                        BeanUtil.copyProperties(personInfo, personTitle);
//                        if (StringUtils.isBlank(personInfo.getName()) || JQNameList.contains(personInfo.getName())) {
//                            continue;
//                        }
//                        if (null != personInfo.getStamp() && 1 == personInfo.getStamp()) {
//                            try {
//                                queryMap = new HashMap<>();
////                                List<Integer> personTitles = iPersonInfoService.getAcademician();
//                                List<Integer> personTitles = new ArrayList<>();
//                                personTitles.add(AcademicianEnum.OUTSTANDING_YOUTH.getCode());
//                                queryMap.put("personTitles", personTitles);
//                                List<PersonInfo> queryPersonInfoList = iPersonInfoService.queryPersonInfoAndCompany(queryMap);
////                                personInfoMap.forEach((key, value) -> {
////                                    if (StringUtils.equals(value, personInfo.getName())) {
////                                        personTitle.setPersonId(key);
////                                        iPersonTitleService.save(personTitle);
////                                        throw new Error();
////                                    }
////                                });
//                            } catch (Error error) {
//                            }
//
//                        } else {
//                            try {
//
////                                personInfoMap.forEach((key, value) -> {
////                                    if (StringUtils.equals(value, personInfo.getName())) {
////                                        List<Long> keyList = new ArrayList<>();
////                                        keyList.add(key);
////                                        queryMap.put("personIds", keyList);
////                                        List<PersonInfo> academPerson = iPersonInfoService.queryPersonInfoAndCompany(queryMap);
////                                        if (StringUtils.equals(academPerson.get(0).getWorkCompany(), personInfo.getWorkCompany()) && StringUtils.equals(academPerson.get(0).getMajor(), personInfo.getMajor()))
////                                            personTitle.setPersonId(key);
////                                        else if (StringUtils.equals(academPerson.get(0).getWorkCompany(), personInfo.getWorkCompany()))
////                                            personTitle.setPersonId(key);
////
////                                        if (null != personTitle.getPersonId())
////                                            throw new Error();
////                                    }
////                                });
//
//                                iPersonInfoService.queryCompany(personInfo);
//                                iPersonInfoService.save(personInfo);
//                                personTitle.setPersonId(personInfo.getId());
//                            } catch (Error error) {
//                            }
//                            if (null != personTitle.getPersonId()) {
//                                iPersonTitleService.save(personTitle);
//                            }
//                        }
//                    }
//                }
////            });
//            }
//        }
//
//        return respJson(CommonEnum.SUCCESS);
//    }

    /**
     * 长江学者-名单入库
     *
     * @return
     */
    @PostMapping("/savePaperInfoByCJ")
    public String savePaperInfoByCJ(@RequestBody String str) {
        try {
            JSONObject jsonObject = new JSONObject();
            if (StringUtils.isNotBlank(str)) {
                jsonObject = JSONObject.parseObject(str);
            }
//            List<PersonInfo> list = new ArrayList<>();

            List<PersonInfo> list = scholarService.crawlerScholar();
            log.info("长江学者-特聘特授人数：{}", list.size());
            List<PersonInfo> list2 = scholarService.crawlerScholarJiangZuo();
            log.info("长江学者-讲座特授人数：{}", list2.size());
            if (CollectionUtils.isNotEmpty(list2)) {
                list.addAll(list2);
            }

            scholarService.updateScholar2011(list, "2011");
            scholarService.updateScholarByYear(list, "2005");
            scholarService.updateScholarByYear(list, "2006");
            scholarService.updateScholarByYear(list, "2007");
            scholarService.updateScholarByYear(list, "2008");
            log.info("筛选2005，2006，2007，2008，2011后长江学者-总人数：{}", list.size());

            //2016年讲座教授和青年学者
            List<PersonInfo> list3 = scholarService.crawlerData();
            log.info("2016年讲座教授和青年学者的人数：{}", list3.size());
            if (CollectionUtils.isNotEmpty(list3)) {
                list.addAll(list3);
            }
            //2017年讲座教授和青年学者
            List<PersonInfo> list4 = scholarService.crawlerData1();
            log.info("2017年讲座教授和青年学者的人数：{}", list4.size());
            if (CollectionUtils.isNotEmpty(list4)) {
                list.addAll(list4);
            }
            //2015年青年学者
            List<PersonInfo> list5 = scholarService.parseData();
            if (CollectionUtils.isNotEmpty(list5)) {
                list.addAll(list5);
            }
            log.info("2015年青年学者的人数：{}", list5.size());
            log.info("长江学者-总人数：{}", list.size());

            List<Integer> academicianList = new ArrayList<>();
            List<PersonTitle> queryPersonTitleList = new ArrayList<>();
            // 院士头衔
            academicianList = iPersonInfoService.getAcademician();
            LambdaQueryWrapper<PersonTitle> personTitleWrapper = new LambdaQueryWrapper<>();
            personTitleWrapper.in(PersonTitle::getAcademicianTitle, academicianList);
            // 查询academicianTitle为是院士的数据
            queryPersonTitleList = iPersonTitleService.list(personTitleWrapper);
            List<Long> academPersonIds = queryPersonTitleList.stream().map(PersonTitle::getPersonId).collect(Collectors.toList());

            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("personIds", academPersonIds);
            if (jsonObject.containsKey("personTitles"))
                queryMap.put("personTitles", jsonObject.get("personTitles"));

            List<PersonInfo> queryPersonInfoList = iPersonInfoService.queryPersonInfoAndCompany(queryMap);
            Map<Long, String> personInfoMap = queryPersonInfoList.stream().collect(Collectors.toMap(PersonInfo::getId, PersonInfo::getName));
            if (MapUtils.isEmpty(personInfoMap)) {
                return respJson(CommonEnum.RESPONSE_CODE_EMPTY, "无院士数据，请检查！");
            }

            // 为长江学者，且为特聘教授
//            LambdaQueryWrapper<Resume> resumeWrapper = new LambdaQueryWrapper<>();
//            resumeWrapper.like(Resume::getResume, "长江学者");
//            resumeWrapper.like(Resume::getResume, "特聘教授");
//            List<Resume> specialHireResumeList = iResumeService.list(resumeWrapper);
//            Set<Long> resumeSet = new HashSet<>();
//            if (CollectionUtils.isNotEmpty(specialHireResumeList)) {
//                List<Long> longList = specialHireResumeList.stream().map(Resume::getPersonId).collect(Collectors.toList());
//                resumeSet = longList.stream().collect(Collectors.toSet());
//            }
//            // 为长江学者，且为讲座教授
//            resumeWrapper = new LambdaQueryWrapper<>();
//            resumeWrapper.like(Resume::getResume, "长江学者");
//            resumeWrapper.like(Resume::getResume, "讲座教授");
//            List<Resume> lectureResumeList = iResumeService.list(resumeWrapper);
//            if (CollectionUtils.isNotEmpty(lectureResumeList)) {
//                List<Long> longList = lectureResumeList.stream().map(Resume::getPersonId).collect(Collectors.toList());
//                Set<Long> set = longList.stream().collect(Collectors.toSet());
//                resumeSet.addAll(set);
//            }
//
//            // 为长江学者，且为特聘教授
//            LambdaQueryWrapper<Honor> honorWrapper = new LambdaQueryWrapper<>();
//            honorWrapper.like(Honor::getPrizeName, "长江学者");
//            honorWrapper.like(Honor::getPrizeName, "特聘教授");
//            List<Honor> specialHireHonorList = iHonorService.list(honorWrapper);
//
//            if (CollectionUtils.isNotEmpty(specialHireHonorList)) {
//                List<Long> longList = specialHireHonorList.stream().map(Honor::getPersonId).collect(Collectors.toList());
//                Set<Long> set = longList.stream().collect(Collectors.toSet());
//                resumeSet.addAll(set);
//            }
//            // 为长江学者，且为讲座教授
//            honorWrapper = new LambdaQueryWrapper<>();
//            honorWrapper.like(Honor::getPrizeName, "长江学者");
//            honorWrapper.like(Honor::getPrizeName, "讲座教授");
//            List<Honor> lectureHonorList = iHonorService.list(honorWrapper);
//            if (CollectionUtils.isNotEmpty(lectureHonorList)) {
//                List<Long> longList = lectureHonorList.stream().map(Honor::getPersonId).collect(Collectors.toList());
//                Set<Long> set = longList.stream().collect(Collectors.toSet());
//                resumeSet.addAll(set);
//            }

            for (PersonInfo personInfo : list) {
                PersonTitle personTitle = new PersonTitle();
                BeanUtil.copyProperties(personInfo, personTitle);

                if (null != personInfo.getStamp() && 1 == personInfo.getStamp()) {
                    try {
                        personInfoMap.forEach((key, value) -> {
                            if (StringUtils.equals(value, personInfo.getName())) {
                                personTitle.setPersonId(key);
                                iPersonTitleService.save(personTitle);
                                throw new Error();
                            }
                        });
                    } catch (Error error) {
                    }

                } else {
                    try {
                        personInfoMap.forEach((key, value) -> {
                            if (StringUtils.equals(value, personInfo.getName())) {
                                List<Long> keyList = new ArrayList<>();
                                keyList.add(key);
                                queryMap.put("personIds", keyList);
                                List<PersonInfo> academPerson = iPersonInfoService.queryPersonInfoAndCompany(queryMap);
                                if (StringUtils.equals(academPerson.get(0).getWorkCompany(), personInfo.getWorkCompany()) && StringUtils.equals(academPerson.get(0).getMajor(), personInfo.getMajor()))
                                    personTitle.setPersonId(key);
                                else if (StringUtils.equals(academPerson.get(0).getWorkCompany(), personInfo.getWorkCompany()))
                                    personTitle.setPersonId(key);

                                if (null != personTitle.getPersonId())
                                    throw new Error();
                            }
                        });

                        iPersonInfoService.queryCompany(personInfo);
                        iPersonInfoService.save(personInfo);
                        personTitle.setPersonId(personInfo.getId());
                    } catch (Error error) {
                    }
                    if (null != personTitle.getPersonId()) {
                        iPersonTitleService.save(personTitle);
                    }
                }
            }
        } catch (IOException e) {
            log.error("savePaperInfoByCJ Exception:{}", e);
        }
        return respJson(CommonEnum.SUCCESS);
    }


    /**
     * 根据模版导入数据，进行新增或更新
     *
     * @return
     */
    @PostMapping("/parseExcelByTemplate")
    public String parseExcelByTemplate(@RequestBody String requestData) throws Exception {
        if (StringUtils.isBlank(requestData))
            return respJson(CommonEnum.PARAM_NULL_ERROR);
        Map map = JSON.parseObject(requestData);
        if (!map.containsKey("filePath") || StringUtils.isBlank(map.get("filePath").toString()))
            return respJson(CommonEnum.PARAM_ERROR, "excel文件路径不能为空！");

        if (!map.containsKey("fileName") || StringUtils.isBlank(map.get("fileName").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称不能为空！");
        } else {
            String fileName = map.get("fileName").toString();
            String fileNamesuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            if (!StringUtils.equalsAny(fileNamesuffix, "xlsx", "xls")) {
                return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称后缀不正确，后缀应该为xlsx或xls ");
            }
        }

        List<PersonInfo> list = scholarService.parseScholarExcel(map.get("filePath").toString() + File.separator + map.get("fileName").toString());
        if (CollectionUtils.isNotEmpty(list)) {
            List<Integer> academicaianList = iPersonInfoService.getAcademician();
            for (PersonInfo personInfo : list) {
//                LambdaQueryWrapper<PersonTitle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//                lambdaQueryWrapper.eq(PersonTitle::getPersonId, personInfo.getId());
//                lambdaQueryWrapper.in(PersonTitle::getAcademicianTitle, academicaianList);
//                // 院士的不处理，原因:院士信息比较全
//                int count = iPersonTitleService.count(lambdaQueryWrapper);
//                if (count > 0)
//                    continue;
                if (StringUtils.isBlank(personInfo.getName()) || JQNameList.contains(personInfo.getName())) {
                    continue;
                }
                iPersonInfoService.queryCompany(personInfo);
                iPersonInfoService.saveOrUpdate(personInfo);
                if (StringUtils.isNotBlank(personInfo.getResume())) {
                    String data = personInfo.getResume();
                    if (data.length() >= 1024) {
                        if (data.indexOf("。") > 0) {
                            String[] datas = data.split("。");
                            for (String str : datas) {
                                iResumeService.queryResumeSave(personInfo, str);
                            }
                        } else if (data.indexOf("；") > 0) {
                            String[] datas = data.split("；");
                            for (String str : datas) {
                                iResumeService.queryResumeSave(personInfo, str);
                            }
                        } else if (data.indexOf(";") > 0) {
                            String[] datas = data.split(";");
                            for (String str : datas) {
                                iResumeService.queryResumeSave(personInfo, str);
                            }
                        }
                    } else {
                        iResumeService.queryResumeSave(personInfo, data);
                    }
                }
                if (StringUtils.isNotBlank(personInfo.getScientificResearchAwards())) {
                    String data = personInfo.getScientificResearchAwards();
                    if (data.length() >= 1024) {
                        if (data.indexOf("。") > 0) {
                            String[] datas = data.split("。");
                            for (String str : datas) {
                                iHonorService.queryHonorSave(personInfo, str, 0);
                            }
                        } else if (data.indexOf("；") > 0) {
                            String[] datas = data.split("；");
                            for (String str : datas) {
                                iHonorService.queryHonorSave(personInfo, str, 0);
                            }
                        } else if (data.indexOf(";") > 0) {
                            String[] datas = data.split(";");
                            for (String str : datas) {
                                iHonorService.queryHonorSave(personInfo, str, 0);
                            }
                        }
                    } else {
                        iHonorService.queryHonorSave(personInfo, data, 0);
                    }
                }
                if (StringUtils.isNotBlank(personInfo.getHonor())) {
                    String data = personInfo.getHonor();
                    if (data.length() >= 1024) {
                        if (data.indexOf("。") > 0) {
                            String[] datas = data.split("。");
                            for (String str : datas) {
                                iHonorService.queryHonorSave(personInfo, str, 1);
                            }
                        } else if (data.indexOf("；") > 0) {
                            String[] datas = data.split("；");
                            for (String str : datas) {
                                iHonorService.queryHonorSave(personInfo, str, 1);
                            }
                        } else if (data.indexOf(";") > 0) {
                            String[] datas = data.split(";");
                            for (String str : datas) {
                                iHonorService.queryHonorSave(personInfo, str, 1);
                            }
                        }
                    } else {
                        iHonorService.queryHonorSave(personInfo, data, 1);
                    }
                }
                if (StringUtils.isNotBlank(personInfo.getSocialService())) {
                    String data = personInfo.getSocialService();
                    if (data.length() >= 1024) {
                        if (data.indexOf("。") > 0) {
                            String[] datas = data.split("。");
                            for (String str : datas) {
                                iSocialService.querySocialSave(personInfo, str);
                            }
                        } else if (data.indexOf("；") > 0) {
                            String[] datas = data.split("；");
                            for (String str : datas) {
                                iSocialService.querySocialSave(personInfo, str);
                            }
                        } else if (data.indexOf(";") > 0) {
                            String[] datas = data.split(";");
                            for (String str : datas) {
                                iSocialService.querySocialSave(personInfo, str);
                            }
                        }
                    } else {
                        iSocialService.querySocialSave(personInfo, data);
                    }
                }
            }
        }
        return respJson(CommonEnum.SUCCESS, "解析模版的总条数：" + list.size());
    }


    /**
     * 批量新增或修改,院士数据
     *
     * @return
     */
    @PostMapping("/parseExcel")
    public String parseExcel(@RequestBody String str) throws Exception {
        JSONObject jsonObject = JSON.parseObject(str);
        Integer start = jsonObject.getInteger("start");
        Integer end = jsonObject.getInteger("end");
        List<PersonInfo> personInfos = parseExcelService.parseExcelSaveDatabase(start, end);
        iPersonInfoService.saveOrUpdateBatch(personInfos);
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 导出院士基本信息
     *
     * @param str
     * @return
     * @throws Exception
     */
    @PostMapping("/exportExcel")
    public String exportExcel(@RequestBody String str) throws Exception {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        JSONObject map = JSON.parseObject(str);
        if (MapUtils.isEmpty(map))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        if (!map.containsKey("type") || StringUtils.isBlank(map.get("type").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出类型(type)不能为空！0：院士信息，1：长江学者，2：杰出青年，3：百人计划，4：科研诚信");
        }

        if (!map.containsKey("filePath") || StringUtils.isBlank(map.get("filePath").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出excel的路径不能为空！");
        }

        if (!map.containsKey("fileName") || StringUtils.isBlank(map.get("fileName").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称不能为空！");
        } else {
            String fileName = map.get("fileName").toString();
            String fileNamesuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            if (!StringUtils.equalsAny(fileNamesuffix, "xlsx", "xls")) {
                return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称后缀不正确，后缀应该为xlsx或xls ");
            }
        }

//        String exportType = map.get("exportType").toString();
//        List<Integer> list = new ArrayList<>();
//        List<PersonInfo> personInfoList = new ArrayList<>();
//        List<PersonTitle> personTitleList = new ArrayList<>();
//        LambdaQueryWrapper<PersonTitle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        switch (exportType) {
//            case "0":
////                lambdaQueryWrapper = new LambdaQueryWrapper<>();
////                lambdaQueryWrapper.in(PersonTitle::getAcademicianTitle, list);
////                personTitleList = iPersonTitleService.list(lambdaQueryWrapper);
////                personInfoList = iPersonTitleService.getPersonTitles(map, personTitleList);
//                list = iPersonInfoService.getAcademician();
//                map.put("personTitles", list);
//                personInfoList = iPersonInfoService.queryExportExcelData(map);
//                break;
//            case "1":
////                lambdaQueryWrapper = new LambdaQueryWrapper<>();
////                lambdaQueryWrapper.in(PersonTitle::getAcademicianTitle, list);
////                personTitleList = iPersonTitleService.list(lambdaQueryWrapper);
////                personInfoList = iPersonTitleService.getPersonTitles(map, personTitleList);
////                personInfoList = iPersonInfoService.customBySql(map);
////                iPersonInfoService.getDetailData(map, personInfoList);
//                list = new ArrayList<>();
//                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_SPECIAL.getCode());
//                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_LECTURE.getCode());
//                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_YOUTH.getCode());
//                list = iPersonInfoService.getAcademician();
//                map.put("personTitles", list);
//                personInfoList = iPersonInfoService.queryExportExcelData(map);
//                break;
//            case "2":
//                list = new ArrayList<>();
//                list.add(AcademicianEnum.OUTSTANDING_YOUTH.getCode());
//                list = iPersonInfoService.getAcademician();
//                map.put("personTitles", list);
//                personInfoList = iPersonInfoService.queryExportExcelData(map);
//                break;
//            case "3":
//                break;
//            case "4":
//                list = new ArrayList<>();
//                list.add(AcademicianEnum.RESEARCH_INTEGRITY.getCode());
//                list = iPersonInfoService.getAcademician();
//                map.put("personTitles", list);
//                personInfoList = iPersonInfoService.queryExportExcelData(map);
//                break;
//        }
        List<PersonInfo> personInfoList = iPersonInfoService.getUpdatePersonInfoData(map);
        iPersonInfoService.getDetailData(map, personInfoList);

        boolean bool = iPersonInfoService.writeExcel(map.get("filePath").toString(), map.get("fileName").toString(), personInfoList);
        if (bool)
            return respJson(CommonEnum.SUCCESS, "导出excel路径：" + map.get("filePath").toString() + File.separator + map.get("fileName").toString());
        else
            return respJson(CommonEnum.FAILURE);
    }


    /**
     * 院士-论文/专利/出版物
     *
     * @return
     */
    @PostMapping("/getPaperPatentInfo")
    public String getPaperPatentInfo(@RequestBody String str) {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        JSONObject jsonObject = JSON.parseObject(str);
        if (null == jsonObject)
            return respJson(CommonEnum.PARAM_NULL_ERROR);

//        if (!jsonObject.containsKey("type")) {
//            return respJson(CommonEnum.PARAM_NULL_ERROR, "type不能为空！0：院士信息，1：长江学者，2：杰出青年，3：百人计划");
//        }

        String type = jsonObject.containsKey("type") ? jsonObject.getString("type"):"";
        List<String> organizationList = new ArrayList<>();
        switch (type) {
            case "0":
                organizationList.add(Constants.ACADEMIC_CAS);
                organizationList.add(Constants.ACADEMIC_CAE);
                break;
            case "1":
                break;
            case "2":
                break;
            case "3":
                break;
        }

        JSONArray resourceJsonArray = new JSONArray();
        if (jsonObject.containsKey("resource")) {
            resourceJsonArray = jsonObject.getJSONArray("resource");
        }
        List<PersonInfo> personInfoList = iPersonInfoService.getUpdatePersonInfoData(jsonObject);
        if (CollectionUtils.isNotEmpty(personInfoList)) {
            for (PersonInfo personInfo : personInfoList) {
                try {
                    // 院士人员，只需要中国科学院、中国工程院就可以，不需要工作单位
                    LambdaQueryWrapper<Company> companyWrapper = new LambdaQueryWrapper<>();
                    companyWrapper.eq(Company::getId, personInfo.getCompanyId());
                    Company company = iCompanyService.getOne(companyWrapper);
                    organizationList.add(company.getCompanyName());
                    Map queryMap = iPaperService.getPaperInfoByUserName(personInfo, resourceJsonArray, organizationList);
                    if (MapUtils.isNotEmpty(queryMap) && queryMap.containsKey("personInfo")) {
                        iPersonInfoService.saveOrUpdate((PersonInfo) queryMap.get("personInfo"));
                    }
                    if (MapUtils.isNotEmpty(queryMap) && queryMap.containsKey("queryPaperJSON")) {
                        JSONObject queryPaperJSON = (JSONObject) queryMap.get("queryPaperJSON");
                        JSONArray resource = queryPaperJSON.getJSONArray("resource");
                        for (int i = 0; i < resource.size(); i++) {
                            queryPaperJSON.remove("resource");
                            JSONArray queryResource = new JSONArray();
                            queryResource.add(resource.get(i));
                            queryPaperJSON.put("resource", queryResource);
                            iPaperService.getPaperPatent(queryPaperJSON, ((PersonInfo) queryMap.get("personInfo")).getId());
                        }
                    }
                } catch (Exception e) {
                    log.error("getPaperInfo - Exception ; {}", e);
                }
            }
        }
        return respJson(CommonEnum.SUCCESS);
    }

    @PostMapping("/checkResume")
    public String checkResume(@RequestBody String str) {
        Map<String, Object> map = JSON.parseObject(str);
        List<Long> personIds = (List) map.get("personIds");
//        List<Integer> personTitles = new ArrayList<>();
//        personTitles.add(AcademicianEnum.CHANGJIANG_SCHOLAR_SPECIAL.getCode());
//        personTitles.add(AcademicianEnum.CHANGJIANG_SCHOLAR_LECTURE.getCode());
//        personTitles.add(AcademicianEnum.CHANGJIANG_SCHOLAR_YOUTH.getCode());
//        Map<String, Object> queryMap = new HashMap<>();
//        queryMap.put("personIds",personIds);
//        queryMap.put("personTitles",personTitles);
//        iPersonInfoService.queryPersonInfoAndCompany(queryMap);
        LambdaQueryWrapper<Resume> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Resume::getPersonId, personIds);
        List<Resume> resumeList = iResumeService.list(lambdaQueryWrapper);
        List<Long> returnList = new ArrayList<>();
        for (int i = 0; i < resumeList.size(); i++) {
            if (!personIds.contains(resumeList.get(i).getPersonId())) {
                returnList.add(resumeList.get(i).getPersonId());
            }
        }
        return respJson(CommonEnum.SUCCESS, returnList);
    }

    /**
     * 根据院士人名与数据库进行匹配，找出未入库的院士人员
     *
     * @param str
     * @return
     */
    @PostMapping("/checkPserson")
    public String checkPserson(@RequestBody String str) {
        Map<String, Object> map = JSON.parseObject(str);
        List<String> queryNameList = (List) map.get("nameList");
//        JSONArray json =  JSON.parseArray(str);
        List<String> nameList = new ArrayList<>();
        List<Long> idList = new ArrayList<>();
//        List<Integer> list = iPersonInfoService.getAcademician();
        List<Integer> list = new ArrayList<>();
        list.add(17);
        map.put("personTitles", list);
        if (map.containsKey("academicianTitles")) {
            map.put("personTitles", map.get("academicianTitles"));
        }
        List<PersonInfo> personInfoList = iPersonInfoService.queryPersonInfoAndCompany(map);
        // 统计姓名出现次数
        Map<String, Long> repeatNameCountMap = personInfoList.stream().collect(Collectors.groupingBy(PersonInfo::getName, Collectors.counting()));
        // 保存重名的姓名
        List<String> repeatNameList = repeatNameCountMap.entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()).collect(Collectors.toList());

        Map<String, Long> resultNameMap = personInfoList.stream().filter(personInfo -> !repeatNameList.contains(personInfo.getName())).collect(Collectors.toMap(PersonInfo::getName, PersonInfo::getId));
//        List<String> resultNameList = personInfoList.stream().map(PersonInfo::getName).collect(Collectors.toList());
//        for (String obj : queryNameList) {
//            // 重名院士
//            if (StringUtils.equalsAny(obj, "陈军", "张杰", "胡文瑞", "陈国良", "李林", "周济"))
//                continue;
////            if (StringUtils.equalsAny(obj, "陈军", "张杰", "胡文瑞"))
////                continue;
//            if (!resultNameList.contains(obj)) {
//                nameList.add(obj);
//            }
//        }
        for (String obj : queryNameList) {
            if (!resultNameMap.containsKey(obj)) {
                nameList.add(obj);
            }
        }

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("nameList", nameList);
//        returnMap.put("idList", nameList);

        return respJson(CommonEnum.SUCCESS, returnMap);
    }


    /**
     * 查询无个人图片的数据id
     *
     * @param str
     * @return
     * @throws IOException
     */
    @PostMapping("/checkPhoto")
    public String checkPhoto(@RequestBody String str) {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        JSONObject jsonObject = JSON.parseObject(str);
        if (null == jsonObject)
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        List<PersonInfo> personInfoList = iPersonInfoService.getUpdatePersonInfoData(jsonObject);
        List<Long> imgList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(personInfoList)) {
            for (PersonInfo personInfo : personInfoList) {
                String fileName = personInfo.getId() + ".jpg";
                File file = new File(imgFilePath + fileName);
                // 判断图片是否存在，如果不存在下载
                if (!file.exists() || StringUtils.isBlank(personInfo.getImgName())) {
                    imgList.add(personInfo.getId());
                }
            }
        }
        return respJson(CommonEnum.SUCCESS, "无图片的数据id:" + JSON.toJSONString(imgList));
    }

    /**
     * 中国工程院院士馆，更新个人信息
     *
     * @param str
     * @return
     * @throws IOException
     */
    @PostMapping("/updateAcademicianHallByPersonInfo")
    public String updateAcademicianHallByPersonInfo(@RequestBody String str) throws IOException {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        JSONObject jsonObject = JSON.parseObject(str);
        if (null == jsonObject)
            return respJson(CommonEnum.PARAM_NULL_ERROR);
        String personName = "";
        if (jsonObject.containsKey("name")) {
            personName = jsonObject.getString("name");
        }
        String electedYear = "";
        if (jsonObject.containsKey("electionYear")) {
            electedYear = jsonObject.getString("electionYear");
        }

        List<PersonInfo> personInfoList = iPersonInfoService.getUpdatePersonInfoData(jsonObject);
        if (CollectionUtils.isNotEmpty(personInfoList)) {
            Map<String, String> params = new HashMap<>();
            if (StringUtils.isNotBlank(electedYear)) {
                // 当选年
                params.put("electedYear", electedYear);
            }
            // 年龄
            params.put("age", "");
            params.put("country", "");
            params.put("origin", "");
            // 性别
            params.put("sex", "");
            // 是否活着，1：活着，0：已逝世
            params.put("isAlive", "");
            params.put("pageSize", "12");
            params.put("pageNum", "1");
            List<Integer> personTitles = iPersonInfoService.getAcademician();
            for (PersonInfo personInfo : personInfoList) {
                //?keywords=[]&electedYear=&age=&country=&origin=&sex=&isAlive=&pageSize=12&pageNum=1&_=1638241111275
                params.put("keywords", personInfo.getName());
                okhttp3.Response response = OkHttp3Util.doGet(Constants.ACADEMICIAN_HALL, params);
                String result = response.body().string();
                if (StringUtils.isBlank(result))
                    log.warn("院士馆查询返回结果为空！");
                JSONObject resultJson = JSON.parseObject(result);
                Integer totalCount = resultJson.containsKey("totalCount") ? resultJson.getInteger("totalCount") : 0;
                if (totalCount > 0) {
                    JSONArray jsonArray = resultJson.getJSONArray("list");
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObj = jsonArray.getJSONObject(i);
                        List typeList = jsonObj.getJSONArray("typeList");
                        String academicianType = AcademicianEnum.getEnum(personInfo.getAcademicianTitle()).getValue();
                        if (academicianType.indexOf("-") > 0)
                            academicianType = academicianType.split("-")[0];

                        // 重名情况，所以必须验证typeList里，是包含中国工程院还是中国科学院，如果都包含说明是两院院士
                        for (int j = 0; j < typeList.size(); j++) {
                            if (StringUtils.contains(typeList.get(j).toString(), academicianType)) {
                                // 院士详情信息id
                                Integer acInfoId = jsonObj.getInteger("acInfoId");
                                // 专业，科学院院士无
                                String speciality = jsonObj.getString("speciality");
                                // 院士个人照片
                                String photoPath = jsonObj.getString("photo");
                                if (StringUtils.isNotBlank(speciality) && StringUtils.isBlank(personInfo.getMajor()))
                                    personInfo.setMajor(speciality);

                                if (StringUtils.isBlank(photoPath)) {
                                    log.error("院士馆photoPath is null 的id：{}", personInfo.getId());
                                }

                                if (StringUtils.isNotBlank(photoPath)) {
                                    photoPath = Constants.ACADEMICIAN_HALL_PHOTO_PREFIX + photoPath;
                                    String fileName = personInfo.getId() + ".jpg";
                                    File file = new File(imgFilePath + fileName);
                                    // 判断图片是否存在，如果不存在下载
                                    if (!file.exists() || StringUtils.isBlank(personInfo.getImgName())) {
                                        CrawlerCommonUtils.getPersonalImgSave(photoPath, imgFilePath, fileName);
                                        personInfo.setImgName(fileName);
                                    }
                                }
                                personalHomeService.getCaePersonalInfo(personInfo, acInfoId.toString());

                                LambdaUpdateWrapper<PersonTitle> updateWrapper = new LambdaUpdateWrapper<>();
                                updateWrapper.in(PersonTitle::getAcademicianTitle, personTitles);
                                updateWrapper.eq(PersonTitle::getPersonId, personInfo.getId());
                                updateWrapper.set(PersonTitle::getElectionYear, personInfo.getElectionYear());
                                updateWrapper.set(PersonTitle::getAcademicianTitle, personInfo.getAcademicianTitle());
                                updateWrapper.set(PersonTitle::getAcademicianTitleValue, personInfo.getAcademicianTitleValue());
                                iPersonTitleService.update(updateWrapper);
                            }
                        }
                    }
                }
            }
        }
        return respJson(CommonEnum.SUCCESS);
    }


    /**
     * 维基百科-更新个人信息
     *
     * @param str
     * @return
     */
    @PostMapping("/updateWiki")
    public String updateWiki(@RequestBody String str) {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        JSONObject jsonObject = JSON.parseObject(str);
        if (null == jsonObject)
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        if (!jsonObject.containsKey("type")) {
            return respJson(CommonEnum.PARAM_NULL_ERROR, "type不能为空！0：院士信息，1：长江学者，2：杰出青年，3：百人计划");
        }
        String type = jsonObject.getString("type");

        List<PersonInfo> personInfoList = iPersonInfoService.getUpdatePersonInfoData(jsonObject);
//         TODO 自定义SQL,更新其它数据
//        List<PersonInfo> personInfoList = iPersonInfoService.customByWikiSql(jsonObject);

        if (CollectionUtils.isNotEmpty(personInfoList)) {
            for (PersonInfo personInfo : personInfoList) {
                try {
                    if (personInfo.getCompanyId() != null) {
                        final LambdaQueryWrapper<Company> lambda2 = new QueryWrapper<Company>().lambda();
                        lambda2.eq(Company::getId, personInfo.getCompanyId());
                        Company company = iCompanyService.getOne(lambda2);
                        if (null != company) {
                            personInfo.setWorkCompany(company.getCompanyName());
                        }
                    }
                    log.info("维基百科查询，url条件：{}，人员id：{}，专业学科：{}，工作单位：{}，姓名：{} ", personInfo.getName() + personInfo.getWorkCompany() + personInfo.getMajor(), personInfo.getId(), personInfo.getMajor(), personInfo.getWorkCompany(), personInfo.getName());
                    // 随机暂停时间，避免维基百科禁用IP
//                    Thread.sleep(CommonUtils.randomRange(1000 * 60, 1000 * 60 * 3));
                    // 爬取维基百科
                    wikipediaCrawlerService.getWikiByPerson(personInfo, Integer.parseInt(type));
                    // 查询人员所在单位是否存在？存在获取company_id;不存在保存所在单位信息;
                    try {
                        iPersonInfoService.queryCompany(personInfo);
                    } catch (Exception e) {
                        log.error("queryCompany 维基百科 Exception:{}", e);
                    }
                    iPersonInfoService.saveOrUpdate(personInfo);
                } catch (Exception e) {
                    log.info("维基百科查询，url条件：{}，人员id：{}，专业学科：{}，工作单位：{}，姓名：{} ，Exception：{}", personInfo.getName() + personInfo.getWorkCompany() + personInfo.getMajor(), personInfo.getId(), personInfo.getMajor(), personInfo.getWorkCompany(), personInfo.getName(), e);
                }
            }
        }
        return respJson(CommonEnum.SUCCESS);

    }

    /**
     * 院士-百度更新个人信息
     *
     * @param str
     * @return
     */
    @PostMapping("/updateBaidu")
    public String updateBaidu(@RequestBody String str) {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        JSONObject jsonObject = JSON.parseObject(str);
        if (null == jsonObject)
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        if (!jsonObject.containsKey("type")) {
            return respJson(CommonEnum.PARAM_NULL_ERROR, "type不能为空！0：院士信息，1：长江学者，2：杰出青年，3：百人计划");
        }
        String type = jsonObject.getString("type");

        List<PersonInfo> personInfoList = iPersonInfoService.getUpdatePersonInfoData(jsonObject);
//         TODO 自定义SQL,更新其它数据
//        List<PersonInfo> personInfoList = iPersonInfoService.customBySql(jsonObject);

        if (CollectionUtils.isNotEmpty(personInfoList)) {
            String filePath = imgFilePath + type + File.separator;
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            for (PersonInfo personInfo : personInfoList) {
                try {
                    if (personInfo.getCompanyId() != null) {
                        final LambdaQueryWrapper<Company> lambda2 = new QueryWrapper<Company>().lambda();
                        lambda2.eq(Company::getId, personInfo.getCompanyId());
                        Company company = iCompanyService.getOne(lambda2);
                        if (null != company) {
                            personInfo.setWorkCompany(company.getCompanyName());
                        }
                    }
                    log.info("百度百科查询，url条件：{}，人员id：{}，专业学科：{}，工作单位：{}，姓名：{} ", personInfo.getName() + personInfo.getWorkCompany() + personInfo.getMajor(), personInfo.getId(), personInfo.getMajor(), personInfo.getWorkCompany(), personInfo.getName());
                    // 随机暂停时间，避免百度禁用IP
                    Thread.sleep(CommonUtils.randomRange(300, 700));
                    // 爬取百度信息
                    baiduCrawlerService.getBaikeByPerson(personInfo, jsonObject, filePath);
                    // 查询人员所在单位是否存在？存在获取company_id;不存在保存所在单位信息;
                    try {
                        iPersonInfoService.queryCompany(personInfo);
                    } catch (Exception e) {
                        log.error("queryCompany 百度百科 Exception:{}", e);
                    }
                    iPersonInfoService.saveOrUpdate(personInfo);
                } catch (Exception e) {
                    log.info("百度百科查询，url条件：{}，人员id：{}，专业学科：{}，工作单位：{}，姓名：{} ，Exception：{}", personInfo.getName() + personInfo.getWorkCompany() + personInfo.getMajor(), personInfo.getId(), personInfo.getMajor(), personInfo.getWorkCompany(), personInfo.getName(), e);
                }
            }
        }
        return respJson(CommonEnum.SUCCESS);

    }


    private void saveData(List<AcademicianEntity> list) {
        for (AcademicianEntity academicianEntity : list) {
            final LambdaQueryWrapper<PersonInfo> lambda = new QueryWrapper<PersonInfo>().lambda();
            PersonInfo personInfo = new PersonInfo();
            BeanUtil.copyProperties(academicianEntity, personInfo);
            lambda.eq(PersonInfo::getName, academicianEntity.getName());
            List<PersonInfo> quertList = iPersonInfoService.list(lambda);
            if (CollectionUtils.isEmpty(quertList)) {
                // 查询人员所在单位是否存在？存在获取company_id;不存在保存所在单位信息;
                iPersonInfoService.queryCompany(personInfo);
                iPersonInfoService.save(personInfo);
                PersonTitle personTitle = new PersonTitle().builder()
                        .personId(personInfo.getId())
                        .academicianTitle(personInfo.getAcademicianTitle())
                        .academicianTitleValue(personInfo.getAcademicianTitleValue())
                        .build();
                iPersonTitleService.save(personTitle);
//            } else {
//                if (quertList.get(0).getAcademicianTitle() != null) {
//                    // 第一次执行时打开，判断是否为两院院士
////                    personInfo.setAcademicianTitle(AcademicianEnum.TWO_CAS_CAE.getCode());
//                }
//                personInfo.setId(quertList.get(0).getId());
//                iPersonInfoService.updateById(personInfo);
            }
        }
    }

//    /**
//     * 更新工程院的院士个人图像
//     *
//     * @param url
//     * @param url2
//     * @param url3
//     * @param toFilePath
//     * @param academicianTitle
//     * @return
//     * @throws IOException
//     */
//    @PostMapping("/updateImg")
//    public String updateImg(String url, String url2, String url3, String toFilePath, String academicianTitle) throws IOException {
//        Map<String, String> map = FileUtil.readFileLines("/crawlerUrlFile/caePersonal.txt", ";");
//
//        String[] titles = academicianTitle.split(",");
//        List<String> titleList = Arrays.asList(titles);
//
//        Map<String, String> nameMap = TestKeXue.cseAcademician(url);
//        Map<String, String> nameMap2 = TestKeXue.cseAcademician(url2);
//        Map<String, String> nameMap3 = TestKeXue.cseAcademician(url3);
//
//        map.forEach((key, value) -> {
//            LambdaQueryWrapper<PersonInfo> lambda = new QueryWrapper<PersonInfo>().lambda();
//            lambda.in(PersonInfo::getAcademicianTitle, titleList);
//            lambda.eq(PersonInfo::getName, key);
//            PersonInfo personInfoOne = iPersonInfoService.getOne(lambda);
//            if (personInfoOne != null && StringUtils.isBlank(personInfoOne.getImgName())) {
//                String urlValue = nameMap.get(personInfoOne.getName());
//                if (StringUtils.isBlank(urlValue)) {
//                    urlValue = nameMap2.get(personInfoOne.getName());
//                }
//                if (StringUtils.isBlank(urlValue)) {
//                    urlValue = nameMap3.get(personInfoOne.getName());
//                }
//                if (StringUtils.isNotBlank(urlValue)) {
////                    String indexPathUrl = RegexUtils.replaceData(PersonalHomeService.indexPath, RegexUtils.ALL_ZHONG_REGEX, urlValue);
//                    Document doc = CrawlerCommonUtils.getDocument("https://www.cae.cn/" + urlValue);
//                    String src = doc.select(".info_img").select("a").select("img").attr("src");
//                    CrawlerCommonUtils.getPersonalImgSave("https://www.cae.cn/" + src, toFilePath + File.separator, personInfoOne.getId() + ".jpg");
//                    personInfoOne.setImgName(personInfoOne.getId() + ".jpg");
//                    iPersonInfoService.saveOrUpdate(personInfoOne);
//                }
//
//            }
//
//        });
//        return respJson(CommonEnum.SUCCESS);
//    }


    @DeleteMapping("/deletePaper")
    public String deletePaper(@RequestBody String str) {
        Long queryPersonId = null;
        if (StringUtils.isNotBlank(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            queryPersonId = jsonObject.getLong("queryPersonId");
        }


        List<Integer> personTitles = iPersonInfoService.getAcademician();
        LambdaQueryWrapper<PersonTitle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(PersonTitle::getAcademicianTitle, personTitles);
        List<PersonTitle> personTitleList = iPersonTitleService.list(lambdaQueryWrapper);
        List<Long> personIdList = personTitleList.stream().map(PersonTitle::getPersonId).collect(Collectors.toList());

        personTitles = new ArrayList<>();
        personTitles.add(AcademicianEnum.CHANGJIANG_SCHOLAR_SPECIAL.getCode());
        personTitles.add(AcademicianEnum.CHANGJIANG_SCHOLAR_LECTURE.getCode());
        personTitles.add(AcademicianEnum.CHANGJIANG_SCHOLAR_YOUTH.getCode());
        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (null != queryPersonId)
            lambdaQueryWrapper.eq(PersonTitle::getPersonId, queryPersonId);
        lambdaQueryWrapper.notIn(PersonTitle::getPersonId, personIdList);
        lambdaQueryWrapper.in(PersonTitle::getAcademicianTitle, personTitles);

        personTitleList = iPersonTitleService.list(lambdaQueryWrapper);
        personIdList = personTitleList.stream().map(PersonTitle::getPersonId).collect(Collectors.toList());

        for (Long personId : personIdList) {
            LambdaQueryWrapper<Paper> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Paper::getPersonId, personId);
            int count = iPaperService.count(wrapper);
            if (count > 100) {
                wrapper.orderBy(true, false, Paper::getPublicationDate);
                List<Paper> paperList = iPaperService.list(wrapper);
                List<Paper> removeList = paperList.subList(100, paperList.size());
                List<Long> paperIds = removeList.stream().map(Paper::getId).collect(Collectors.toList());
                wrapper = new LambdaQueryWrapper<>();
                wrapper.in(Paper::getId, paperIds);

                iPaperService.remove(wrapper);
            }
            LambdaQueryWrapper<Publication> pwrapper = new LambdaQueryWrapper<>();
            pwrapper.eq(Publication::getPersonId, personId);
            count = iPublicationService.count(pwrapper);
            if (count > 100) {
                List<Publication> paperList = iPublicationService.list(pwrapper);
                List<Publication> removeList = paperList.subList(100, paperList.size());
                List<Long> paperIds = removeList.stream().map(Publication::getId).collect(Collectors.toList());
                pwrapper = new LambdaQueryWrapper<>();
                pwrapper.in(Publication::getId, paperIds);
                iPublicationService.remove(pwrapper);
            }
            LambdaQueryWrapper<Patent> patentWrapper = new LambdaQueryWrapper<>();
            patentWrapper.eq(Patent::getPersonId, personId);
            count = iPatentService.count(patentWrapper);
            if (count > 100) {
                List<Patent> paperList = iPatentService.list(patentWrapper);
                List<Patent> removeList = paperList.subList(100, paperList.size());
                List<Long> paperIds = removeList.stream().map(Patent::getId).collect(Collectors.toList());
                patentWrapper = new LambdaQueryWrapper<>();
                patentWrapper.in(Patent::getId, paperIds);
                iPatentService.remove(patentWrapper);
            }
        }

        return respJson(CommonEnum.SUCCESS);
    }

    @PostMapping("/youthJQ")
    public String youthJQ(@RequestBody String str) {
        String queryYear = null;
        if (StringUtils.isNotBlank(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
//            if (null != jsonObject || jsonObject.size() > 0) {
//                queryYear = jsonObject.getString("queryYear");
//                File outstandYouthFile = new File(outstandYouthPath + "youth-" + queryYear + ".txt");
//                if (outstandYouthFile.exists()) {
//                    try {
//                        List<String> yearYouthList = FileUtils.readLines(outstandYouthFile, StandardCharsets.UTF_8);
//                        Map<String, PersonInfo> nameMap = new HashMap<>();
//                        for (String line : yearYouthList) {
//                            aminerCrawlerService.parseAminerTxt(line, nameMap, queryYear);
//                        }
//
//                        if (MapUtils.isNotEmpty(nameMap)) {
//                            List<PersonInfo> personInfoList = nameMap.entrySet().stream().map(entry->entry.getValue()).collect(Collectors.toList());
//                            iPersonInfoService.verifyDuplicateNamesAndSaveOrUpdate(personInfoList);
//                        }
//
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
        }

        List<PersonInfo> list = jqCrawlerService.crawlerOutstanTalents();
        Map<String, List<PersonInfo>> personInfoGroupMap = list.stream().collect(Collectors.groupingBy(PersonInfo::getElectionYear));

        for(Map.Entry<String, List<PersonInfo>> entryMap : personInfoGroupMap.entrySet()) {
            String yearValue = entryMap.getKey();
            List<PersonInfo> personInfoList = entryMap.getValue();
            Map<String, PersonInfo> nameMap = new HashMap<>();
            // 同年重名人员，2019:石峰、张龙，2014:张强，2009:汪国平，2007：王伟，暂不处理，也没有几个手动解决
            if (StringUtils.equals(yearValue, "2019")) {
                nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
                        && !StringUtils.equalsAny(personInfo.getName(), "石峰", "张龙"))
                        .collect(Collectors.toMap(PersonInfo::getName, x -> x));
            } else if (StringUtils.equals(yearValue, "2014")) {
                nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
                        && !StringUtils.equalsAny(personInfo.getName(), "张强"))
                        .collect(Collectors.toMap(PersonInfo::getName, x -> x));
            } else if (StringUtils.equals(yearValue, "2009")) {
                nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
                        && !StringUtils.equalsAny(personInfo.getName(), "汪国平"))
                        .collect(Collectors.toMap(PersonInfo::getName, x -> x));
            } else if (StringUtils.equals(yearValue, "2007")) {
                nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp()
                        && !StringUtils.equalsAny(personInfo.getName(), "王伟"))
                        .collect(Collectors.toMap(PersonInfo::getName, x -> x));
            } else {
                nameMap = personInfoList.stream().filter(personInfo -> null == personInfo.getStamp())
                        .collect(Collectors.toMap(PersonInfo::getName, x -> x));
            }
            File outstandYouthFile = new File(outstandYouthPath + "youth-" + yearValue + ".txt");
//            File outstandYouthFile = new File( "E:\\project\\crawler\\src\\main\\resources\\htmlTest\\jq-杰出青年\\" + "youth-" + yearValue + ".txt");
            if (outstandYouthFile.exists()) {
                try {
                    List<String> yearYouthList = FileUtils.readLines(outstandYouthFile, StandardCharsets.UTF_8);
                    for (String line : yearYouthList) {
                        aminerCrawlerService.parseAminerTxt(line, nameMap, yearValue);
                    }
                } catch (IOException e) {
                    log.error("youthJQ Exception：{}", e);
                    return respJson(CommonEnum.ERROR);
                }
            }
            personInfoList = nameMap.entrySet().stream().map(entry -> entry.getValue()).collect(Collectors.toList());
        }

        personInfoGroupMap.forEach((yearValue, personInfoList) -> {
            // 两院院士中的杰青
            List<PersonInfo> updatePersonInfoList = personInfoList.stream().filter(personInfo -> personInfo.getStamp() != null && personInfo.getStamp() == 1).collect(Collectors.toList());
            Map<String, Object> queryMap = new HashMap<>();
            for (int i = 0; i < updatePersonInfoList.size(); i++) {
                queryMap.put("name", updatePersonInfoList.get(i).getName());
                List<PersonInfo> queryPersonInfoList = iPersonInfoService.queryPersonInfoAndCompany(queryMap);
                List<PersonInfo> youthList = queryPersonInfoList.stream().filter(personInfo -> personInfo.getAcademicianTitle() != null && personInfo.getAcademicianTitle() == 12).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(youthList)) {
                    Map<Long, PersonInfo> personInfoMap = queryPersonInfoList.stream().collect(Collectors.toMap(PersonInfo::getId, a -> a, (key1, key2) -> key1));
                    List<PersonInfo> updateList = personInfoMap.entrySet().stream().map(entry -> entry.getValue()).collect(Collectors.toList());
                    PersonTitle personTitle = new PersonTitle().builder()
                            .personId(updateList.get(0).getId())
                            .academicianTitle(AcademicianEnum.OUTSTANDING_YOUTH.getCode())
                            .academicianTitleValue(AcademicianEnum.OUTSTANDING_YOUTH.getValue())
                            .titleYears(AcademicianEnum.OUTSTANDING_YOUTH.getTitleYears())
                            .electionYear(yearValue)
                            .build();
                    iPersonTitleService.save(personTitle);
                }
            }

            // 过滤掉已确定为院士的数据
            List<PersonInfo> savePersonInfoList = personInfoList.stream().filter(personInfo -> personInfo.getStamp() == null).collect(Collectors.toList());
            iPersonInfoService.verifyDuplicateNamesAndSaveOrUpdate(savePersonInfoList);
        });
        return respJson(CommonEnum.SUCCESS);
    }


    @PostMapping("/updateRelatedLinks")
    public String updateRelatedLinks(@RequestBody String str) {
        List<PersonInfo> personInfoList = iPersonInfoService.list();
        for (PersonInfo personInfo : personInfoList) {
            if (StringUtils.isNotBlank(personInfo.getRelatedLinks())) {
                String links = personInfo.getRelatedLinks();
                try {
                    JSONObject jsonObject = JSON.parseObject(links);
                    JSONArray jsonArray = new JSONArray();
                    jsonArray.add(jsonObject);
                    personInfo.setRelatedLinks(JSON.toJSONString(jsonArray));
                    iPersonInfoService.saveOrUpdate(personInfo);
                } catch (Exception e) {
                }
            }
        }
        return respJson(CommonEnum.SUCCESS);
    }


    @PostMapping("/parseSchoolPersonExcel")
    public String parseSchoolPersonExcel(@RequestBody String str) {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);
        Map map = JSON.parseObject(str);
        if (!map.containsKey("filePath") || StringUtils.isBlank(map.get("filePath").toString()))
            return respJson(CommonEnum.PARAM_ERROR, "excel文件路径不能为空！");

        if (!map.containsKey("fileName") || StringUtils.isBlank(map.get("fileName").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称不能为空！");
        } else {
            String fileName = map.get("fileName").toString();
            String fileNamesuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            if (!StringUtils.equalsAny(fileNamesuffix, "xlsx", "xls")) {
                return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称后缀不正确，后缀应该为xlsx或xls ");
            }
        }

        List<PersonInfo> list = parseExcelService.parseSchoolPersonExcel(map.get("filePath").toString() + File.separator + map.get("fileName").toString());
//        Map<String, Long> count = list.stream().collect(Collectors.groupingBy(PersonInfo::getWorkCompany, Collectors.counting()));
//        System.out.println(JSON.toJSONString(count));
        if (CollectionUtils.isNotEmpty(list)) {
            iPersonInfoService.verifyDuplicateNamesAndSaveOrUpdate(list);
        }
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<PersonInfo> lambda, PersonInfoReqVo param) {
        if (null != (param.getId())) {
            lambda.eq(PersonInfo::getId, param.getId());
        }
        if (null != (param.getCompanyId())) {
            lambda.eq(PersonInfo::getCompanyId, param.getCompanyId());
        }
        if (!StringUtils.isEmpty(param.getName())) {
            lambda.eq(PersonInfo::getName, param.getName());
        }
        if (null != (param.getAcademicianTitle())) {
            lambda.eq(PersonInfo::getAcademicianTitle, param.getAcademicianTitle());
        }
        if (!StringUtils.isEmpty(param.getSex())) {
            lambda.eq(PersonInfo::getSex, param.getSex());
        }
        if (!StringUtils.isEmpty(param.getNation())) {
            lambda.eq(PersonInfo::getNation, param.getNation());
        }
        if (!StringUtils.isEmpty(param.getForeignName())) {
            lambda.eq(PersonInfo::getForeignName, param.getForeignName());
        }
        if (!StringUtils.isEmpty(param.getNationality())) {
            lambda.eq(PersonInfo::getNationality, param.getNationality());
        }
        if (!StringUtils.isEmpty(param.getBirthday())) {
            lambda.eq(PersonInfo::getBirthday, param.getBirthday());
        }
        if (!StringUtils.isEmpty(param.getBirthplace())) {
            lambda.eq(PersonInfo::getBirthplace, param.getBirthplace());
        }
        if (!StringUtils.isEmpty(param.getDateOfDeath())) {
            lambda.eq(PersonInfo::getDateOfDeath, param.getDateOfDeath());
        }
        if (!StringUtils.isEmpty(param.getImgName())) {
            lambda.eq(PersonInfo::getImgName, param.getImgName());
        }
        if (!StringUtils.isEmpty(param.getSchool())) {
            lambda.eq(PersonInfo::getSchool, param.getSchool());
        }
        if (!StringUtils.isEmpty(param.getDepartment())) {
            lambda.eq(PersonInfo::getDepartment, param.getDepartment());
        }
        if (!StringUtils.isEmpty(param.getMajor())) {
            lambda.eq(PersonInfo::getMajor, param.getMajor());
        }
        if (!StringUtils.isEmpty(param.getPersonTitle())) {
            lambda.eq(PersonInfo::getPersonTitle, param.getPersonTitle());
        }
        if (!StringUtils.isEmpty(param.getAcademicDegree())) {
            lambda.eq(PersonInfo::getAcademicDegree, param.getAcademicDegree());
        }
        if (!StringUtils.isEmpty(param.getPoliticalParty())) {
            lambda.eq(PersonInfo::getPoliticalParty, param.getPoliticalParty());
        }
        if (null != (param.getStatus())) {
            lambda.eq(PersonInfo::getStatus, param.getStatus());
        }
        if (null != (param.getDelFlag())) {
            lambda.eq(PersonInfo::getDelFlag, param.getDelFlag());
        }
        if (!CollectionUtils.isEmpty(param.getCreateTimeList())) {
            lambda.ge(PersonInfo::getCreateTime, param.getCreateTimeList().get(0));
            lambda.le(PersonInfo::getCreateTime, param.getCreateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getCreateUser())) {
            lambda.eq(PersonInfo::getCreateUser, param.getCreateUser());
        }
        if (!CollectionUtils.isEmpty(param.getUpdateTimeList())) {
            lambda.ge(PersonInfo::getUpdateTime, param.getUpdateTimeList().get(0));
            lambda.le(PersonInfo::getUpdateTime, param.getUpdateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getUpdateUser())) {
            lambda.eq(PersonInfo::getUpdateUser, param.getUpdateUser());
        }
        lambda.orderBy(true, false, PersonInfo::getId);
    }


    /**
     * 请求model
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    private static class PersonInfoReqVo extends PersonInfo {
        private List<String> createTimeList; // 创建时间起止
        private List<String> updateTimeList; // 修改时间起止
    }


}
